package com.ts.api.module.channel.entity.vo;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.ts.api.module.channel.entity.bo.ChannelListFormFieldValueBO;
import com.ts.api.module.channel.entity.po.ChannelFormFieldPO;
import lombok.Data;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *  表单字段值对象
 *
 *  @author Pan
 */
@Data
public class RespChannelFormFieldValueVO {

    /** 表单id */
    private Long id;
    /** 映射名称 */
    private String mappingName;
    /** 表单名称 */
    private String fieldName;
    /** 表单类型 */
    private String type;
    /** 表单值 */
    private List<ChannelListFormFieldValueBO> listFieldValue;
    /** 用户已选中值 */
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private Long selectValueId;

    /**
     *  转换返回前端VO
     *
     *  @param  list
     *  @return List
     */
    public static List<RespChannelFormFieldValueVO> convertVO(List<ChannelFormFieldPO> list) {
        List<RespChannelFormFieldValueVO> listVO = new ArrayList<>();

        Map<Long, List<ChannelFormFieldPO>> collect = list.stream().collect(Collectors.groupingBy(t -> t.getId()));
        Iterator<Map.Entry<Long, List<ChannelFormFieldPO>>> iterator = collect.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Long, List<ChannelFormFieldPO>> next = iterator.next();
            List<ChannelFormFieldPO> value = next.getValue();

            RespChannelFormFieldValueVO channelFormFieldValueVO = new RespChannelFormFieldValueVO();
            channelFormFieldValueVO.setId(next.getKey());

            //  获取字段值对象
            List<ChannelListFormFieldValueBO> listFieldValue = new ArrayList<>();
            for (ChannelFormFieldPO formField: value) {
                channelFormFieldValueVO.setMappingName(formField.getMappingName());
                channelFormFieldValueVO.setFieldName(formField.getFieldName());
                channelFormFieldValueVO.setType(formField.getType());

                ChannelListFormFieldValueBO channelListFormFieldValueBO = new ChannelListFormFieldValueBO();
                channelListFormFieldValueBO.setFieldValueId(formField.getFieldValueId());
                channelListFormFieldValueBO.setFieldValue(formField.getFieldValue());
                listFieldValue.add(channelListFormFieldValueBO);
            }
            channelFormFieldValueVO.setListFieldValue(listFieldValue);

            listVO.add(channelFormFieldValueVO);
        }
        return listVO;
    }

}
